// 菜单管理API接口
import type { Menu, MenuFormData } from '../types/menu';
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';
import { menuData } from '../data/menuData';

// 菜单API基础路径
const MENU_API_BASE = `${getAPI_BASE_URL_SYNC()}/menus`;

// API请求参数接口
export interface GetMenusParams {
  page?: number;
  pageSize?: number;
  search?: string;
  type?: number;
  status?: number;
  parentId?: string | number;
}

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 菜单列表响应格式
interface MenuListResponse {
  menus: Menu[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 菜单模拟API实现
const mockMenuApi = {
  async getMenus(params: GetMenusParams = {}): Promise<ApiResponse<Menu[]>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { page = 1, pageSize = 10, search, type, status, parentId } = params;
    
    // 过滤数据
    let filteredData = [...menuData];
    
    if (search) {
      filteredData = filteredData.filter(menu => 
        menu.name.toLowerCase().includes(search.toLowerCase()) ||
        menu.description?.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    if (type !== undefined) {
      filteredData = filteredData.filter(menu => menu.type === type);
    }
    
    if (status !== undefined) {
      filteredData = filteredData.filter(menu => menu.status === status);
    }
    
    if (parentId !== undefined) {
      filteredData = filteredData.filter(menu => menu.parentId === parentId);
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取菜单列表成功'
    };
  },

  async getMenuTree(): Promise<ApiResponse<Menu[]>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    // 构建菜单树
    const buildTree = (menus: Menu[], parentId: string | number | null = null): Menu[] => {
      return menus
        .filter(menu => menu.parentId === parentId)
        .map(menu => ({
          ...menu,
          children: buildTree(menus, menu.id)
        }));
    };
    
    const treeData = buildTree(menuData);
    
    return {
      data: treeData,
      total: treeData.length,
      success: true,
      message: '获取菜单树成功'
    };
  },

  async getMenu(menuId: string | number): Promise<ApiResponse<Menu>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const menu = menuData.find(m => m.id === menuId);
    if (!menu) {
      throw new Error('菜单不存在');
    }
    
    return {
      data: menu,
      total: 1,
      success: true,
      message: '获取菜单详情成功'
    };
  },

  async createMenu(menuData: MenuFormData): Promise<ApiResponse<Menu>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const newMenu: Menu = {
      id: Date.now().toString(),
      name: menuData.name,
      path: menuData.path,
      icon: menuData.icon || '',
      type: menuData.type || 1,
      parentId: menuData.parentId || null,
      sort: menuData.sort || 0,
      status: 1,
      description: menuData.description || '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    menuData.push(newMenu);
    
    return {
      data: newMenu,
      total: 1,
      success: true,
      message: '菜单创建成功'
    };
  },

  async updateMenu(menuId: string | number, menuData: Partial<MenuFormData>): Promise<ApiResponse<Menu>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = menuData.findIndex(menu => menu.id === menuId);
    if (index === -1) {
      throw new Error('菜单不存在');
    }
    
    menuData[index] = { ...menuData[index], ...menuData, updatedAt: new Date().toISOString() };
    
    return {
      data: menuData[index],
      total: 1,
      success: true,
      message: '菜单信息更新成功'
    };
  },

  async deleteMenu(menuId: string | number): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = menuData.findIndex(menu => menu.id === menuId);
    if (index === -1) {
      throw new Error('菜单不存在');
    }
    
    menuData.splice(index, 1);
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '菜单删除成功'
    };
  },

  async toggleMenuStatus(menuId: string | number, status: number): Promise<ApiResponse<Menu>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = menuData.findIndex(menu => menu.id === menuId);
    if (index === -1) {
      throw new Error('菜单不存在');
    }
    
    menuData[index].status = status;
    menuData[index].updatedAt = new Date().toISOString();
    
    return {
      data: menuData[index],
      total: 1,
      success: true,
      message: `菜单状态已${status === 1 ? '启用' : '禁用'}`
    };
  }
};

export const menuApi = {
  // 获取菜单列表（支持分页、搜索、筛选）
  async getMenus(params: GetMenusParams = {}): Promise<ApiResponse<Menu[]>> {
    if (shouldUseMockServer()) {
      return mockMenuApi.getMenus(params);
    }
    try {
      const { page = 1, pageSize = 10, search, type, status, parentId } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });
      
      if (search) queryParams.append('search', search);
      if (type !== undefined) queryParams.append('type', type.toString());
      if (status !== undefined) queryParams.append('status', status.toString());
      if (parentId !== undefined) queryParams.append('parentId', parentId.toString());
      
      const url = `${MENU_API_BASE}?${queryParams.toString()}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<MenuListResponse>>(url);
      
      // 根据后端API响应格式调整
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        // 如果后端返回的是标准格式
        const menuList = backendData.data;
        return {
          data: menuList?.menus || [],
          total: menuList?.total || 0,
          success: true,
          message: backendData.message || '获取菜单列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取菜单列表失败');
      }
    } catch (error) {
      console.error('获取菜单列表失败:', error);
      
      // 如果后端API不可用，返回空数据（开发阶段）
      return {
        data: [],
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取菜单列表失败'
      };
    }
  },

  // 获取菜单树形结构
  async getMenuTree(): Promise<ApiResponse<Menu[]>> {
    if (shouldUseMockServer()) {
      return mockMenuApi.getMenuTree();
    }
    try {
      const url = `${MENU_API_BASE}/tree`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<Menu[]>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data || [],
          total: backendData.data?.length || 0,
          success: true,
          message: backendData.message || '获取菜单树成功'
        };
      } else {
        throw new Error(backendData.message || '获取菜单树失败');
      }
    } catch (error) {
      console.error('获取菜单树失败:', error);
      throw new Error(error instanceof Error ? error.message : '获取菜单树失败');
    }
  },

  // 获取单个菜单详情
  async getMenu(menuId: string | number): Promise<ApiResponse<Menu>> {
    if (shouldUseMockServer()) {
      return mockMenuApi.getMenu(menuId);
    }
    try {
      const url = `${MENU_API_BASE}/${menuId}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<Menu>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '获取菜单详情成功'
        };
      } else {
        throw new Error(backendData.message || '获取菜单详情失败');
      }
    } catch (error) {
      console.error('获取菜单详情失败:', error);
      throw new Error(error instanceof Error ? error.message : '获取菜单详情失败');
    }
  },

  // 创建菜单
  async createMenu(menuData: MenuFormData): Promise<ApiResponse<Menu>> {
    if (shouldUseMockServer()) {
      return mockMenuApi.createMenu(menuData);
    }
    try {
      // 发送POST请求
      const response = await http.post<BackendApiResponse<Menu>>(MENU_API_BASE, menuData);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '菜单创建成功'
        };
      } else {
        throw new Error(backendData.message || '创建菜单失败');
      }
    } catch (error) {
      console.error('创建菜单失败:', error);
      throw new Error(error instanceof Error ? error.message : '创建菜单失败');
    }
  },

  // 更新菜单
  async updateMenu(menuId: string | number, menuData: Partial<MenuFormData>): Promise<ApiResponse<Menu>> {
    if (shouldUseMockServer()) {
      return mockMenuApi.updateMenu(menuId, menuData);
    }
    try {
      const url = `${MENU_API_BASE}/${menuId}`;
      
      // 发送PUT请求
      const response = await http.put<BackendApiResponse<Menu>>(url, menuData);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '菜单信息更新成功'
        };
      } else {
        throw new Error(backendData.message || '更新菜单失败');
      }
    } catch (error) {
      console.error('更新菜单失败:', error);
      throw new Error(error instanceof Error ? error.message : '更新菜单失败');
    }
  },

  // 删除菜单
  async deleteMenu(menuId: string | number): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockMenuApi.deleteMenu(menuId);
    }
    try {
      const url = `${MENU_API_BASE}/${menuId}`;
      
      // 发送DELETE请求
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '菜单删除成功'
        };
      } else {
        throw new Error(backendData.message || '删除菜单失败');
      }
    } catch (error) {
      console.error('删除菜单失败:', error);
      throw new Error(error instanceof Error ? error.message : '删除菜单失败');
    }
  },

  // 切换菜单状态
  async toggleMenuStatus(menuId: string | number, status: number): Promise<ApiResponse<Menu>> {
    if (shouldUseMockServer()) {
      return mockMenuApi.toggleMenuStatus(menuId, status);
    }
    try {
      const url = `${MENU_API_BASE}/${menuId}/status`;
      
      // 发送PATCH请求更新状态
      const response = await http.patch<BackendApiResponse<Menu>>(url, { status });
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || `菜单状态已${status === 1 ? '启用' : '禁用'}`
        };
      } else {
        throw new Error(backendData.message || '切换菜单状态失败');
      }
    } catch (error) {
      console.error('切换菜单状态失败:', error);
      throw new Error(error instanceof Error ? error.message : '切换菜单状态失败');
    }
  }
};